<?php
/**
 *
 * Standard facebook connect class, this is not an official replacement for the Facebook PHP SDK
 * @author AFV <saviorfromthenorth@yahoo.com.ph>
 * @version 0.0.4
 */
class fToolkit
{
    public $id;
    public $token;

    private $code;
    public $settings = array();
    public $signedRequest = array();

    /**
     *
     * Initialize Facebook Connect
     */
    public function __construct()
    {
        //Allow MSIE 3rd party cookies
        if (!headers_sent() && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
            header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');

        $this->settings = parse_ini_file('settings.ini');
        
        if (empty($this->settings))
            $this->error('settings.ini is empty');
            
        if (isset($_SERVER['HTTP_REFERER'])) {
            if ($_SERVER['HTTP_REFERER'] == 'http://static.ak.facebook.com/platform/page_proxy.php?v=4') {
                $redirectURI = $this->settings['fan_page'];
            } else {
                $redirectURI = $this->settings['canvass_page'];
            }
        } else {
            $redirectURI = $this->settings['canvass_url'];
        }

        $dialogURL = "http://www.facebook.com/dialog/oauth?" .
        			 "client_id="     . $this->settings['app_id'] .
        			 "&redirect_uri=" . urlencode($redirectURI) .
        			 "&scope="        . $this->settings['app_scope'];

        if (isset($_COOKIE['fb-token'])) {
            $this->id    = $_COOKIE['fb-id'];
            $this->token = $_COOKIE['fb-token'];
        } else if (isset($_REQUEST['signed_request'])) {
            list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);

            $sig     = base64_decode(strtr($encoded_sig, '-_', '+/'));
            $sigUser = json_decode(base64_decode(strtr($payload, '-_', '+/'), true), true);

            $this->token = $sigUser['oauth_token'];
            $this->id    = $sigUser['user_id'];
            
            $this->signedRequest = $sigUser;
            
            if (empty($this->id)) {
                echo '<script type="text/javascript">top.location.href = "' . $dialogURL . '"</script>';
                exit(1);
            }
        } else if (isset($_REQUEST['code'])) {
            $tokenURL = "https://graph.facebook.com/oauth/access_token?" .
                        "&client_id="     . $this->settings['app_id'].
                        "&client_secret=" . $this->settings['app_secret'] .
                        "&redirect_uri="  . urlencode($redirectURI) .
                        "&code="          . $_REQUEST['code'];
            $token    = @file_get_contents($tokenURL);
            $token    = explode("&", $token);
            $token    = explode("=", $token[0]);

            $this->token = $token[1];

            $data     = $this->api('me');
            $this->id = $data["id"];
        } else {
            if ($redirectURI == $this->settings['canvass_page']) {
                echo '<script type="text/javascript">top.location.href = "' . $dialogURL . '"</script>';
            } else {
                header("Location: $dialogURL");
            }
            exit(1);
        }

        //failsafe cookies
        if (!isset($_COOKIE['fb-id']) && !headers_sent()) {
            setcookie('fb-id', $this->id, time() + 3600);
            setcookie('fb-token', $this->token, time() + 3600);
        }
    }

    /**
     *
     * Query information through Graph API
     * @param $param graph parameters
     * @return array
     */
    public function api($param = "")
    {
        $graphURL = "https://graph.facebook.com/" . $param . "?access_token=" . $this->token;
        return json_decode(@file_get_contents($graphURL), true);
    }

    /**
     *
     * Publish to feed using cURL
     * @param $params publish parameters
     * @return array
     */
    public function publish($params = array())
    {
        if (empty($params)) {
            return false;
        } else {
            $params['access_token'] = $this->token;

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/me/feed");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 6);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

            $data = curl_exec($ch);

            curl_close($ch);

            return $data;
        }
    }

    /**
     *
     * Check wether current user is a Fan of the page specified
     * @param $pageID Object ID of page to be query
     * @return abstract
     */
    public function isPageFan($pageID)
    {
        $fan = $this->fql("SELECT created_time FROM page_fan WHERE page_id = $pageID AND uid = " . $this->id);
        return empty($fan) ? false : $fan[0]['created_time'];
    }

    /**
     *
     * Build FQL query link
     * @param $query Query string
     * @return string
     */
    public function fql($query)
    {
        $fqlURL = "https://api.facebook.com/method/fql.query?query=" . urlencode($query) . "&access_token=" . $this->token . "&format=JSON";
        return json_decode(@file_get_contents($fqlURL), true);
    }

    /**
     *
     * Perform CURLOPT
     * @param $link URL to be crawled
     * @param string
     */
    private function runCurl($link)
    {
        $ch      = curl_init();
        $timeout = 5;

        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

        $data = curl_exec($ch);

        curl_close($ch);

        return $data;
    }

    public function upload($image)
    {
        $fieldString['image'] = '@' . $image;

        $ch = curl_init();
        curl_setopt($ch ,CURLOPT_URL, "https://graph.facebook.com/" . $this->id . "/photos?access_token=" . $this->token);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 6);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldString);

        $data = curl_exec($ch);

        curl_close($ch);

        return $data;
    }
    
    public function error($message)
    {
        echo '<b>Error:</b> ' . $message;
        exit(1);
    }
}
